package com.yiwei.ydd.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.webkit.WebView;



import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.UUID;

import com.yiwei.ydd.Application;


/**
 * Created by MasterDong on 16/8/4.
 */
public class RBInfo {

    private Context mContext;
    private String token = "";
    private WebView webView;

    private static RBInfo instance;

    public static synchronized RBInfo getInstance() {
        if (instance == null) {
            instance = new RBInfo(Application.getInstance());
        }
        return instance;
    }

    private RBInfo(Context context) {
        mContext = context;
    }


    /**
     * 获取Token
     *
     * @return
     */
    public String getToken() {
        if (TextUtils.isEmpty(PreferenceUtils.getString(mContext, "token", ""))) {
            if (TextUtils.isEmpty(getUniquePsuedoID()))
                token = MD5.getMD5str(getMac() + Util.getRandomNum(100000, 999999) + "");
            else
                token = MD5.getMD5str(getUniquePsuedoID() + Util.getRandomNum(100000, 999999));
            PreferenceUtils.putString(mContext, "token", token);
        } else {
            token = PreferenceUtils.getString(mContext, "token", "");
        }
        return token;
    }


    /**
     * 获取设备唯一id
     *
     * @return 设备唯一id
     */
    public String getDeviceId() {
        try {
            final TelephonyManager tm = (TelephonyManager) mContext
                    .getSystemService(Context.TELEPHONY_SERVICE);

            final String tmDevice, tmSerial, androidId;
            tmDevice = "" + tm.getDeviceId();
//            tmSerial = "" + tm.getSimSerialNumber();
//            androidId = ""
//                    + android.provider.Settings.Secure.getString(
//                    mContext.getContentResolver(),
//                    android.provider.Settings.Secure.ANDROID_ID);
//
//            UUID deviceUuid = new UUID(androidId.hashCode(),
//                    ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
//            return deviceUuid.toString();
            return tmDevice;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 检查网络是否可用
     *
     * @return
     */
    public boolean checkEnable() {
        boolean i = false;
        NetworkInfo localNetworkInfo = ((ConnectivityManager) mContext
                .getSystemService(mContext.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if ((localNetworkInfo != null) && (localNetworkInfo.isAvailable()))
            return true;
        return false;
    }

    public  String getIPAddress() {
        NetworkInfo info = ((ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    /**
     * 获取UserAgent
     *
     * @return
     */
    public String getUserAgent() {
        if (webView == null) webView = new WebView(mContext);
        String user_agent = webView.getSettings().getUserAgentString();
        return user_agent;
    }

    /**
     * 系统版本
     *
     * @return
     */
    public String getOSVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 获取移动设备的品牌
     *
     * @return
     */
    public String getModel() {
        return Build.MODEL;
    }

    /**
     * 获取移动设备的型号
     *
     * @return
     */
    public String getBrand() {
        return Build.BRAND;
    }


    /**
     * 获取手机的MAC地址
     *
     * @return
     */
    public String getMac() {
        String str = "";
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (macSerial == null || "".equals(macSerial)) {
            try {
                return loadFileAsString("/sys/class/net/eth0/address")
                        .toUpperCase().substring(0, 17);
            } catch (Exception e) {
                e.printStackTrace();

            }

        }
        return macSerial;
    }

    private String loadFileAsString(String fileName) throws Exception {
        try {
            FileReader reader = new FileReader(fileName);
            String text = loadReaderAsString(reader);
            reader.close();
            return text;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    private String loadReaderAsString(Reader reader) throws Exception {
        try {
            StringBuilder builder = new StringBuilder();
            char[] buffer = new char[4096];
            int readLength = reader.read(buffer);
            while (readLength >= 0) {
                builder.append(buffer, 0, readLength);
                readLength = reader.read(buffer);
            }
            return builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 获得独一无二的Psuedo ID
     *
     * @return
     */
    public String getUniquePsuedoID() {
        String serial = null;

        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        try {
            serial = Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }


    public String getNativePhoneNumber() {
        TelephonyManager telephonyManager = (TelephonyManager) mContext
                .getSystemService(Context.TELEPHONY_SERVICE);
        String NativePhoneNumber=null;
        NativePhoneNumber=telephonyManager.getLine1Number();
        return NativePhoneNumber;
    }
}
